import {
  areaData
} from '../../../config/index';
import Toast from 'tdesign-miniprogram/toast/index';
import {
  baseURL
} from '../../../services/request'
import {
  addTerminalDetail,
  getTerminalDetail,
  editTerminal
} from '../../../services/api/menber'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    visible: false,
    areaData: areaData,
    areaPickerVisible: false,
    userList: [],
    popvisible: false,
    isEdit: false,
    showSaveBtn: false,
    kid: "",
    agentUserId: '',
    personInfo: {
      customerName: '',
      addr: '',
      area: "",
      city: "",
      province: "",
      phone: "",
      empUserId: "",
      memo: "",
      intentionProductIds: '1,2',
      agentUserId: "",
      subdistrictBuildingNumber: "",
      subdistrictHouseNumber: "",
      subdistrictName: ""
    },
    locationState: {
      labelIndex: null,
      addressId: '',
      addressTag: '',
      cityCode: '',
      cityName: '',
      countryCode: '',
      countryName: '',
      detailAddress: '',
      districtCode: '',
      districtName: '',
      isDefault: false,
      name: '',
      phone: '',
      provinceCode: '',
      provinceName: '',
      isEdit: false,
      isOrderDetail: false,
      isOrderSure: false,
    },
    typeVisible: false,
  },
  onInputChange(e) {
    const key = e.currentTarget.dataset.key,
      value = e.detail.value;
    this.setData({
      [key]: value
    })
  },
  handleChange(e) {
    console.log(e, 'e')
    this.setData({
      priceLevel: e.detail.value,
    });
  },
  editStatus() {
    this.setData({
      isEdit: false,
      showSaveBtn: true
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    this.setData({
      agentUserId: options.agentUserId
    })
    if (options.isEdit) {
      this.getDetailData(options);
      wx.setNavigationBarTitle({
        title: '编辑终端客户',
      })
    } else {
      this.setData({
        showSaveBtn: true,
      })
    }
    // this.getAllUserList();
  },
  // async getAllUserList() {
  //   let {
  //     data
  //   } = await getAgent({});
  //   let index = data.findIndex((el) => el.key == this.data.personInfo.pid);
  //   this.setData({
  //     userList: data,
  //     upperAgent: index >= 0 ? data[index].value : ''
  //   })
  // },
  onChange(e) {
    console.log(e.detail.value, 'e');
    this.data.userList.forEach((el) => {
      if (el.key == e.detail.value) {
        this.setData({
          popvisible: false,
          pid: e.detail.value,
          upperAgent: el.value
        })
      }
    })

  },
  async getDetailData(options) {
    let {
      code,
      data
    } = await getTerminalDetail({
      kid: options.kid
    });
    this.setData({
      isEdit: options.isEdit,
      personInfo: data,
      kid: options.kid,
      locationState: {
        cityCode: data.cityCode,
        cityName: data.city,
        countryCode: '',
        countryName: '',
        detailAddress: data.addr,
        districtCode: data.areaCode,
        districtName: data.area,
        isDefault: false,
        provinceCode: data.provinceCode,
        provinceName: data.province,
        isEdit: false,
        isOrderDetail: false,
        isOrderSure: false,
      },
    });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onInputValue(e) {
    const {
      item
    } = e.currentTarget.dataset;
    if (item === 'address') {
      const {
        selectedOptions = []
      } = e.detail;
      this.setData({
        'locationState.provinceCode': selectedOptions[0].value,
        'locationState.provinceName': selectedOptions[0].label,
        'locationState.cityName': selectedOptions[1].label,
        'locationState.cityCode': selectedOptions[1].value,
        'locationState.districtCode': selectedOptions[2].value,
        'locationState.districtName': selectedOptions[2].label,
        areaPickerVisible: false,
      }, );
    } else {
      const {
        value = ''
      } = e.detail;
      this.setData({
        [`locationState.${item}`]: value,
      }, );
    }
  },
  onPickArea() {
    this.setData({
      areaPickerVisible: true
    });
  },


  onClose() {
    this.setData({
      typeVisible: false,
    });
  },
  onVisibleChange(e) {
    this.setData({
      popvisible: e.detail.visible,
    });
  },



  save() {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    const role = wx.getStorageSync('role');
    let patten = /^[1][3,4,5,7,8,9][0-9]{9}$/;
    if (!this.data.personInfo.phone ||
      !this.data.personInfo.customerName ||
      !this.data.personInfo.addr ||
      !this.data.personInfo.subdistrictName ||
      !this.data.personInfo.subdistrictBuildingNumber ||
      !this.data.personInfo.subdistrictHouseNumber
    ) {
      Toast({
        selector: '#t-toast',
        message: '请填写正确的手机号码',
        icon: '',
        duration: 1000,
      });
      return;
    };


    if (!patten.test(this.data.personInfo.phone)) {
      Toast({
        selector: '#t-toast',
        message: '请填写正确的手机号码',
        icon: '',
        duration: 1000,
      });
      return;
    };
    let params = {
      ...this.data.personInfo,
      agentUserId: this.data.agentUserId,
      province: this.data.locationState.provinceName,
      provinceCode: this.data.locationState.provinceCode,
      city: this.data.locationState.cityName,
      cityCode: this.data.locationState.cityCode,
      area: this.data.locationState.districtName,
      areaCode: this.data.locationState.districtCode,
      empUserId: 1,
    };
    console.log(params);
    if (options.isEdit) {
      //  编辑
      this.editData(params)
    } else {
      // 新增
      this.saveData(params)
    }
  },
  async editData(params) {
    let res = await editTerminal({
      ...params,
      kid: this.data.kid
    });
    if (res.code == '200') {
      wx.navigateTo({
        url: `/subpages/pages/allTerminal/allTerminal?agentUserId=${this.data.agentUserId}`,
      })
    }
  },

  async saveData(params) {
    let res = await addTerminalDetail(params);
    if (res.code == '200') {
      wx.navigateTo({
        url: `/subpages/pages/allTerminal/allTerminal?agentUserId=${this.data.agentUserId}`,
      })
    }
  },

})